package com.onlinevideo.servlet;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.multipart.UploadFile;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.MyConst;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.util.VCodeUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileServlet extends BaseServlet{

    private PrintWriter writer = null ;

    protected void uploadImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        if(!ServletUtil.isMultipart(req)){
            writer.write(JSONUtil.toJsonPrettyStr(ResultBean.scUploadError("文件上传失败，请求方法非POST或文件类下非‘multipart/*’")));
            return;
        }
        //获取参数名为file的文件对象
        UploadFile oldFile = ServletUtil.getMultipart(req).getFile("file");
        //设置图片的上传不允许超过50M
        if(oldFile.size()>1024*1024*50){
            writer.write(JSONUtil.toJsonPrettyStr(ResultBean.scUploadError("文件上传失败，文件大小不要允许超过50M")));
            return;
        }
        BufferedInputStream bin = new BufferedInputStream(oldFile.getFileInputStream());
        //设置新建文件的文件名称
        String oldFileName = oldFile.getFileName();
        String newFileName = System.currentTimeMillis()+oldFileName.substring(oldFileName.lastIndexOf(".") );
        //磁盘存取路径
        String path = MyConst.FILE_UPLOAD_PATH+newFileName;
        File newFile = new File(path);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
        byte[] b=new byte[2048];
        int n=0;
        while ((n=bin.read(b))!=-1){
            bos.write(b,0,n);
            bos.flush();
        }
        //通过判断文件是否存在判断是否上传成功
        if(newFile.exists()){
            writer.write(JSONUtil.toJsonPrettyStr(ResultBean.scUploadSuccess("文件上传成功",newFileName)));
        }else {
            writer.write(JSONUtil.toJsonPrettyStr(ResultBean.scUploadError("文件上传失败")));
        }
        bos.close();
        bin.close();
    }

    //生成图片验证码方法
    protected void verifyCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置图片大小
        BufferedImage image  =new BufferedImage(180,60,BufferedImage.TYPE_INT_RGB);
        //生成画笔
        Graphics2D g = (Graphics2D) image.getGraphics();
        //设置画笔颜色
        g.setColor(Color.white);
        //用画笔填充背景颜色
        g.fillRect(0,0,180,60);
        //获得方法
        String vCode = VCodeUtils.getVCode(6);
        char[] chars = vCode.toCharArray();
        Random random = new Random();
        //基础间隔
        int left = 15;
        int rAngle = 0;
        //六个字符分别设置格式
        for (int i = 0; i < chars.length; i++) {
            g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200))); //设置字体颜色
            rAngle = random.nextInt(90)-45;
            int top = random.nextInt(25) + 30;
            String[] fonts = MyConst.FONTS;
            g.setFont(new Font(fonts[random.nextInt(fonts.length)],random.nextInt(3),random.nextInt(10)+30));//设置字体类型
            g.rotate(rAngle * Math.PI / 180,left,top);
            //设置填充的数据以及填充数据的位置
            g.drawString(String.valueOf(chars[i]), left , top);
            g.rotate(-rAngle * Math.PI / 180,left,top);
            left+=random.nextInt(10)+20;
            g.setColor(new Color(random.nextInt(100)+150, random.nextInt(100)+150, random.nextInt(100)+150)); //设置字体颜色
            g.setStroke(new BasicStroke(3.0f,BasicStroke.CAP_SQUARE,BasicStroke.JOIN_BEVEL));
            g.drawLine(random.nextInt(180),random.nextInt(60),random.nextInt(180),random.nextInt(60));


        }
        //把验证码通过Cookie发送到浏览器
        resp.addCookie(new Cookie("vCode",vCode));
        //发送图片
        resp.setContentType("image/jpeg");
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    protected void getQrServlet(HttpServletRequest req, HttpServletResponse resp) throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException {
        String result2= HttpUtil.get("https://server01.vicy.cn/8lXdSX7FSMykbl9nFDWESdc6zfouSAEz/wxLogin/tempUserId?secretKey=07c1274b284c443784fdf55216022c9f", CharsetUtil.CHARSET_UTF_8);
        System.out.println(result2);
        JSONObject jsonObject = JSONUtil.parseObj(result2);
        //cid
        JSONObject jsonData = jsonObject.getJSONObject("data");
        String qrCodeReturnUrl2 = String.valueOf(jsonData.get("qrCodeReturnUrl"));
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis()));
        String path = "D:\\\\uploadFile\\\\images\\\\temp\\"+date;
        File file = new File(path);
        if(!file.exists()){
          file.mkdirs();
        }
        File file1 = FileUtil.file(path+"\\"+System.currentTimeMillis()+".jpg");
        QrCodeUtil.generate(qrCodeReturnUrl2, 300, 300, file1);
        BufferedImage image  = ImageIO.read(file1);
        resp.setContentType("image/jpeg");
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }

    /**
     * 下载office文件
     * @param req 请求体
     * @param resp 向响应体
     */
    protected void uploadOffice(HttpServletRequest req, HttpServletResponse resp)  {

    }
    protected void uploadVideo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
